<template>
  <div style="padding: 10px; height: 100%; display: flex; flex-direction: column; justify-content: space-between;">
    <el-form ref="cameraPatrolTaskFormRef" :model="form" :rules="rules" label-width="110px" :inline="true" style="display: flex; flex-direction: column;">
      <div>
        <el-form-item label="任务名称" prop="patrolTaskName">
          <el-input v-model="form.patrolTaskName" placeholder="请输入巡视任务名称" style="width: 245px;"/>
        </el-form-item>
        <el-form-item label="执行时间" prop="startAndEndTimeAdd" >
          <el-time-picker v-model="startAndEndTimeAdd" is-range range-separator="-" value-format="HH:mm:ss" style="min-width: 245px;width: 245px;" @change="handleDateChangeTimeAdd" />
        </el-form-item>
        <el-form-item label="任务周期" prop="startAndEndAdd">
          <el-date-picker v-model="startAndEndAdd" type="daterange" start-placeholder="开始日期" end-placeholder="结束日期" value-format="YYYY-MM-DD" @change="handleDateChangeAdd" />
          <div>
            <el-checkbox v-model="form.mondayFlag" label="星期一" value="0"/>
            <el-checkbox v-model="form.tuesdayFlag" label="星期二" value="0"/>
            <el-checkbox v-model="form.wednesdayFlag" label="星期三" value="0"/>
            <el-checkbox v-model="form.thursdayFlag" label="星期四" value="0"/>
            <el-checkbox v-model="form.fridayFlag" label="星期五" value="0"/>
            <el-checkbox v-model="form.saturdayFlag" label="星期六" value="0"/>
            <el-checkbox v-model="form.sundayFlag" label="星期日" value="0"/>
          </div>
        </el-form-item>

        <el-form-item label="执行人" prop="executeUserId">
          <el-input v-model="form.executeUserName" filterable clearable placeholder="请选择执行人" style="width: 245px; margin-right: 20px; pointer-events: none;" />
          <el-button type="primary" @click="openAddAuditor">请选择</el-button>
<!--          <el-select v-model="form.executeUserId" placeholder="请选择执行人" style="width: 245px;">-->
<!--            <el-option v-for="item in optionsExcuteUserList" :key="item.userId" :label="item.nickName" :value="item.userId" />-->
<!--          </el-select>-->
        </el-form-item>
        <el-form-item label="任务状态" prop="cameraPatrolTaskStatus">
          <el-select v-model="form.cameraPatrolTaskStatus" placeholder="请选择任务状态" style="width: 245px;">
            <el-option v-for="dict in camera_patrol_task_status" :key="dict.value" :label="dict.label" :value="dict.value" ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否要求打卡" prop="clockFlag">
          <el-select v-model="form.clockFlag" placeholder="请选择打卡要求" style="width: 245px;">
            <el-option v-for="dict in clock_flag" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" >
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" style="width: 630px;"/>
        </el-form-item>
      </div>
      <el-form-item label="选择巡视路线" prop="cameraPatrolRouteId" >
        <el-table ref="myTable" v-loading="loading" :data="cameraPatrolRouteList" @selection-change="handleSelectionRouteChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="路线名称" align="center" prop="patrolRouteName" show-overflow-tooltip/>
          <el-table-column label="路线描述" align="center" prop="patrolRouteDesc" show-overflow-tooltip/>
          <el-table-column label="调用摄像头" align="center" prop="cameraNameS" show-overflow-tooltip/>
        </el-table>

        <div style="width: 100%; height: 50px; display: flex; justify-content: flex-end; align-items: center;">
          <pagination v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" size="small" layout="total, prev, pager, next" @pagination="getRouteList"/>
        </div>
      </el-form-item>
    </el-form>

    <div style="height: 50px; width: 100%; display: flex; justify-content: center; align-items: center;">
      <el-button :loading="buttonLoading" :disabled="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button :loading="buttonLoading" :disabled="buttonLoading" @click="emit('close')">取 消</el-button>
    </div>

    <!-- 执行人选择弹窗 -->
    <UserSelect ref="singleUserSelectRef" :data="form.executeUserId" :role-key-list="['security-patrol']" :multiple="false" @confirm-call-back="selectExecuteUser"></UserSelect>
  </div>
</template>

<script setup  lang="ts">
import { addcameraPatrolTask } from '@/api/security/video-patrol/camera-patrol-task';
import { listUser } from '@/api/system/user';
import { listpatrolroute } from '@/api/security/video-patrol/camera-patrol-route';
import { patrolrouteQuery, patrolrouteForm } from '@/api/security/video-patrol/camera-patrol-route/types';
import { cameraPatrolTaskQuery, cameraPatrolTaskForm } from '@/api/security/video-patrol/camera-patrol-task/types';
import UserSelect from '@/components/UserSelect/index.vue'

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { camera_patrol_task_status, clock_flag } = toRefs<any>(proxy?.useDict('camera_patrol_task_status', 'clock_flag'));

const buttonLoading = ref(false);
const loading = ref(true);
const myTable = ref()
const total = ref(0)
const cameraPatrolTaskFormRef = ref<ElFormInstance>();

const emit = defineEmits(['close', 'success']);

const initFormData: any = {
  cameraPatrolTaskId: undefined,
  remark: undefined,
  patrolTaskName: undefined,
  executeRoleId: undefined,
  executeUserName: null
}
const data = reactive<any>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    patrolTaskName: undefined,
    executeRoleId: undefined,
    startAndEnd: undefined,
    params: {
    }
  },
  rules: {
    patrolTaskName: [
      { required: true, message: '巡视任务名称不能为空', trigger: 'blur' }
    ],
    startAndEndAdd: [
      { required: true, message: '任务周期不能为空', trigger: 'blur' }
    ],
    startAndEndTimeAdd: [
      { required: true, message: '执行时间不能为空', trigger: 'change' }
    ],
    cameraPatrolTaskStatus: [
      { required: true, message: '任务状态不能为空', trigger: 'change' }
    ],
    executeUserId: [
      { required: true, message: '执行人不能为空', trigger: 'change' }
    ],
    clockFlag: [
      { required: true, message: '是否要求打卡不能为空', trigger: 'change' }
    ],
    cameraPatrolRouteId: [
      { required: true, message: '请选择路线', trigger: 'change' }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 多选框选中数据 */
const handleSelectionRouteChange = (selection: any) => {
  selection.map((row: any, index: number)=> {
    if (selection.length <= 1) {
      return
    }
    // toggleRowSelection 用于多选表格，切换某一行的选中状态， 如果使用了第二个参数，则可直接设置这一行选中与否
    myTable.value.toggleRowSelection(row, false)
    if (index === selection.length - 1) {
      myTable.value.toggleRowSelection(row, true)
    }
  })

  if (selection.length >= 1) {
    form.value.cameraPatrolRouteId = selection[0].cameraPatrolRouteId
  }
}

/** 详情 */
const cameraPatrolTaskInfo = () => {
  form.value.mondayFlag = true;
  form.value.tuesdayFlag = true;
  form.value.wednesdayFlag = true;
  form.value.thursdayFlag = true;
  form.value.fridayFlag = true;
  form.value.saturdayFlag = true;
  form.value.sundayFlag = true;

  getExecuteUserList()
  getRouteList()
}

/**
 * 选择审批人
 */
const singleUserSelectRef = ref<any>();
const openAddAuditor = () => {
  singleUserSelectRef.value.open();
}

/**
 * 选择审批人
 */
const selectExecuteUser = (data: any[]) => {
  let executeUser = data.length !== 0 ? data[0] : undefined;
  form.value.executeUserName = executeUser?.nickName;
  form.value.executeUserId = executeUser?.userId
};

/** 提交按钮 */
const submitForm = () => {
  cameraPatrolTaskFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.fridayFlag) {
        form.value.fridayFlag = '0'
      } else {
        form.value.fridayFlag = '1'
      }
      if (form.value.mondayFlag) {
        form.value.mondayFlag = '0'
      } else {
        form.value.mondayFlag = '1'
      }
      if (form.value.sundayFlag) {
        form.value.sundayFlag = '0'
      } else {
        form.value.sundayFlag = '1'
      }
      if (form.value.fridayFlag) {
        form.value.fridayFlag = '0'
      } else {
        form.value.fridayFlag = '1'
      }
      if (form.value.tuesdayFlag) {
        form.value.tuesdayFlag = '0'
      } else {
        form.value.tuesdayFlag = '1'
      }
      if (form.value.saturdayFlag) {
        form.value.saturdayFlag = '0'
      } else {
        form.value.saturdayFlag = '1'
      }
      if (form.value.thursdayFlag) {
        form.value.thursdayFlag = '0'
      } else {
        form.value.thursdayFlag = '1'
      }
      if (form.value.wednesdayFlag) {
        form.value.wednesdayFlag = '0'
      } else {
        form.value.wednesdayFlag = '1'
      }

      await addcameraPatrolTask(form.value).finally(() => buttonLoading.value = false);
      proxy?.$modal.msgSuccess('操作成功');
      emit('close');
      emit('success', form.value);
    }
  });
}

/** 日期框改变 */
let startAndEndAdd = ref([])
const handleDateChangeAdd = () => {
  form.value.startTime = startAndEndAdd.value[0]
  form.value.endTime = startAndEndAdd.value[1]
  form.value.startAndEndAdd = startAndEndAdd
}

/** 日期框改变 */
let startAndEndTimeAdd = ref([])
const handleDateChangeTimeAdd = () => {
  form.value.executionStartTime = startAndEndTimeAdd.value[0]
  form.value.executionEndTime = startAndEndTimeAdd.value[1]
  form.value.startAndEndTimeAdd = startAndEndTimeAdd
}

/** 路线分页 */
const dataRoute = reactive<PageData<patrolrouteForm, patrolrouteQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    patrolRouteName: undefined,
    patrolRouteDesc: undefined,
    params: {
    }
  },
  rules: {
  }
});
let cameraPatrolRouteList = ref([])
const getRouteList = async() => {
  const res = await listpatrolroute(dataRoute.queryParams).finally(() => loading.value = false);
  cameraPatrolRouteList.value = res.rows
  total.value = res.total
}

/** 执行用户 */
let optionsExecuteUserList = ref([])
const getExecuteUserList = async() => {
  const res = await listUser()
  console.log('获取执行用户：', res)
  optionsExecuteUserList.value = res.rows
}

onMounted(() => {
  cameraPatrolTaskInfo();
});
</script>
<style lang="scss" scoped>

</style>
